import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from time import sleep
import re
import os

#模拟加载网页
s = Service('./chromedriver.exe')
driver = webdriver.Chrome(service=s)
driver.get(
    'https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&dyTabStr=MCwxLDUsNiw0LDMsNyw4LDIsOQ%3D%3D&word=%E5%B7%A5%E4%B8%9A%E7%8E%B0%E5%9C%BA%E5%8D%B1%E9%99%A9%E5%8C%BA%E5%9F%9F%E4%BA%BA%E5%91%98')
for i in range(0,500): #按页爬取，一次一页
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
    sleep(1)
sleep(3)
page = driver.page_source
    
#匹配图片地址
ex = 'data-imgurl="(.*?)"'
img_src_list = re.findall(ex,page, re.S)
print(img_src_list)
#遍历地址，下载图片
for src in img_src_list:
    img_data = requests.get(src).content
    img_name = re.search('[0-9]*', src.split(',')[-1])
    img_name = img_name.group(0)
    img_path = 'image' + '/' + img_name + '.jpg'
    with open(img_path, 'wb') as fp:
        fp.write(img_data)
        print('ok')